const voteOptions = document.getElementById('voteOptions');
const feedbackEl = document.getElementById('feedback');
let submitting = false;
let optionsList = [];

function getVoteIdFromUrl() {
  const url = new URL(window.location.href);
  const vid = url.searchParams.get('voteId');
  return vid;
}

function showFeedback(message, variant = 'info') {
  feedbackEl.textContent = message;
  feedbackEl.className = `feedback ${variant}`;
}

function getVoterId() {
  // 简单用localStorage生成唯一ID
  let id = localStorage.getItem('voter_id');
  if (!id) {
    id = 'voter_' + Math.random().toString(36).slice(2) + Date.now();
    localStorage.setItem('voter_id', id);
  }
  return id;
}

function renderOptions() {
  voteOptions.innerHTML = '';
  if (!Array.isArray(optionsList) || optionsList.length === 0) {
    showFeedback('暂无投票选项。', 'error');
    return;
  }
  optionsList.forEach(opt => {
    const btn = document.createElement('button');
    btn.className = 'vote-button';
    btn.textContent = opt.name;
    btn.onclick = () => handleVote(opt.id, opt.name, btn);
    btn.disabled = submitting;
    voteOptions.appendChild(btn);
  });
  showFeedback('请选择投票选项。', 'info');
}

async function handleVote(option_id, optionName, btn) {
  if (submitting) return;
  submitting = true;
  btn.disabled = true;
  showFeedback(`正在为 ${optionName} 投票...`, 'info');
  try {
    const voter_id = getVoterId();
    const voteId = getVoteIdFromUrl();
    const endpoint = voteId ? `/api/votes/${encodeURIComponent(voteId)}/vote` : '/api/vote';
    const res = await fetch(endpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ voter_id, option_id })
    });
    const data = await res.json();
    if (!res.ok) {
      showFeedback(data.message || '投票失败', 'error');
    } else {
      showFeedback('投票成功！', 'success');
      // 禁用所有按钮
      document.querySelectorAll('.vote-button').forEach(b => b.disabled = true);
    }
  } catch (e) {
    showFeedback('网络异常，投票失败', 'error');
  } finally {
    submitting = false;
  }
}

async function loadOptions() {
  try {
    const voteId = getVoteIdFromUrl();
    if (voteId) {
      const res = await fetch(`/api/votes/${encodeURIComponent(voteId)}/options`);
      optionsList = await res.json();
    } else {
      const res = await fetch('/api/options');
      optionsList = await res.json();
    }
    renderOptions();
  } catch (e) {
    showFeedback('获取投票选项失败', 'error');
  }
}

loadOptions();
